<script setup>
import {reactive} from "vue";
// 获取本地存储数据
const localGoods = reactive(JSON.parse(localStorage.getItem("goods")) || []);
// 获取商品数据
const goods = (await fetch("/api/goods").then(res=>res.json())).data;
// 准备存放，要渲染的数据
const renderGoods = reactive([]);
// 将本地存储数据和商品数据对比，过滤出需要渲染的数据
localGoods.forEach(val1=>{
  goods.forEach(val2=>{
    if(val1.id === val2.goodsId){
      renderGoods.push({
        id: val1.id,
        name: val2.goodsName,
        img: val2.goodsImg,
        check: val1.check,
        num: val1.num,
        price: val1.price
      })
    }
  })
})

// 增加数量
function add(id){
  renderGoods[ getIndex(id) ].num++;
  changeLocal();
}

// 减少数量
function diff(id){
  renderGoods[ getIndex(id) ].num--;
  changeLocal();
}

// 改变本地存储
function changeLocal(){
  const g = renderGoods.map(val=>{
    return {
      id:val.id,
      check:val.check,
      price:val.price,
      num:val.num
    }
  })
  localStorage.setItem("goods", JSON.stringify(g));
}

// 根据id获取商品数据的索引
function getIndex(id){
  let i=0;
  renderGoods.some((val,idx)=>{
    i = idx;
    return val.id === id
  })
  return i;
}
</script>

<template>
  <div class="cart">
    <h1>这是购物车</h1>
    <table border="1" width="800">
      <thead>
        <tr>
          <th width="34">选中</th>
          <th>图片</th>
          <th>名称</th>
          <th width="70">数量</th>
          <th>价格</th>
          <th>小计</th>
          <th>操作</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="item in renderGoods" :key="item.id">
          <td><input type="checkbox" v-model="item.check" @change="changeLocal"></td>
          <td><img :src="item.img" alt=""></td>
          <td>{{ item.name }}</td>
          <td>
            <input type="button" value="-" @click="diff(item.id)">
            <span>{{ item.num }}</span>
            <input type="button" value="+" @click="add(item.id)">
          </td>
          <td>{{ item.price }}</td>
          <td>{{ item.price * item.num }}</td>
          <td>删除</td>
        </tr>
      </tbody>
      <tfoot>
        <tr>
          <td><input type="checkbox" id="c"></td>
          <td><label for="c">全选</label></td>
          <td align=right>总数量：</td>
          <td>0</td>
          <td align=right>总价：</td>
          <td>0</td>
          <td>删除选中</td>
        </tr>
      </tfoot>
    </table>
  </div>
</template>

<style>
img{width:40px;}
</style>
